package com.bw.seckill.controller;


import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bw.common.ResponseResult;
import com.bw.common.aliPay.AlipayConfig;
import com.bw.common.idwork.IdWorker;
import com.bw.seckill.entity.TbSeckillGoods;
import com.bw.seckill.entity.TbSeckillOrder;
import com.bw.seckill.entity.TbSeckillOrderReq;
import com.bw.seckill.service.ITbSeckillGoodsService;
import com.bw.seckill.service.ITbSeckillOrderService;
import com.bw.seckill.service.ITbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xingjinning
 * @since 2020-07-14
 */
@RestController
@RequestMapping("/order")
@CrossOrigin
public class TbSeckillOrderController {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private RedisTemplate<String,Object> objectRedisTemplate;

    @Autowired
    private ITbSeckillOrderService orderService;
    @Autowired
    private ITbSeckillGoodsService goodsService;
    @Autowired
    private ITbUserService userService;
    @Autowired
    private IdWorker idWorker;

    @PostMapping("purchase/{gid}/{uid}")
    public ResponseResult saveOrder(@PathVariable("gid")long gid,@PathVariable("uid")long uid){
        ResponseResult result = ResponseResult.SUCCESS();
        try {
            TbSeckillGoods seckillGoods = goodsService.getById(gid);
            TbSeckillOrder tbSeckillOrder = new TbSeckillOrder();
            tbSeckillOrder.setCode(idWorker.nextId()+"");
            tbSeckillOrder.setGoodsId(gid);
            tbSeckillOrder.setUserId(uid);
            tbSeckillOrder.setStatus((long) 0);
            tbSeckillOrder.setAmount(seckillGoods.getCostPrice());
            tbSeckillOrder.setCreateTime(new Date());
            orderService.saveOrUpdate(tbSeckillOrder);
            seckillGoods.setStockNum(seckillGoods.getStockNum()-1);
            goodsService.saveOrUpdate(seckillGoods);
            result.setMessage("保存订单成功");
        }catch (Exception e){
            result=ResponseResult.FAIL();
        }
        return result;
    }
    @GetMapping("/findOrder/{uid}")
    public ResponseResult findOrder(@PathVariable("uid")long uid){
        ResponseResult result = ResponseResult.SUCCESS();
        List<TbSeckillOrderReq> list = orderService.findOrder(uid);
        result.setResult(list);
        return result;
    }
    @GetMapping("getVal")
    public String findOrderss(){
        Map map = new HashMap<>();
        map.put("name","zhansgan");
        map.put("age",18);
        redisTemplate.opsForHash().put("k3","1",map);
        redisTemplate.opsForValue().set("k2","v2");
        return redisTemplate.opsForValue().get("k2");
    }
    @GetMapping("getVal01")
    public Map findOrders(){
        Map map = new HashMap<>();
        map.put("name","zhansgan");
        map.put("age",18);
        objectRedisTemplate.opsForValue().set("k4",map);
        return (Map) objectRedisTemplate.opsForValue().get("k4");
    }
    @PostMapping("payMoney")
    public ResponseResult list(@RequestBody TbSeckillOrderReq orderReq){

        ResponseResult result = ResponseResult.SUCCESS();

        QueryWrapper queryWrapper = new QueryWrapper();
        try {
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(AlipayConfig.return_url);
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);



            alipayRequest.setBizContent("{\"out_trade_no\":\""+ orderReq.getCode() +"\","
                    + "\"total_amount\":\""+ orderReq.getCostPrice()+"\","
                    + "\"subject\":\""+ "支付钱" +"\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");


            String results = alipayClient.pageExecute(alipayRequest).getBody();
            TbSeckillOrder order = orderService.getById(orderReq.getId());

            order.setStatus((long) 1);


            orderService.saveOrUpdate(order);
            result.setResult(results);
        }catch (Exception e){
            result=ResponseResult.FAIL();
        }

        return result;
    }

}
